<template>
  <div class="process-designer">
    <div class="toolbar">
      <button @click="newDiagram" class="btn">新建流程</button>
      <button @click="saveDiagram" class="btn">保存流程</button>
      <button @click="deployDiagram" class="btn btn-primary">部署流程</button>
    </div>
    <div class="editor-container">
      <div id="canvas" class="canvas"></div>
      <div id="properties-panel-parent" class="properties-panel"></div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue';
import BpmnModeler from 'bpmn-js/lib/Modeler';
import { workflowService } from '../api/workflowService';
import { BpmnPropertiesPanelModule, BpmnPropertiesProviderModule } from 'bpmn-js-properties-panel';
import minimapModule from 'diagram-js-minimap';
import BpmnModelerModules from 'bpmn-js/lib/features/modeling';

// 导入BPMN样式
import 'bpmn-js/dist/assets/diagram-js.css';
import 'bpmn-js/dist/assets/bpmn-font/css/bpmn.css';
import 'bpmn-js/dist/assets/bpmn-font/css/bpmn-codes.css';
import 'bpmn-js/dist/assets/bpmn-font/css/bpmn-embedded.css';
import '@bpmn-io/properties-panel/assets/properties-panel.css';
import 'diagram-js-minimap/assets/diagram-js-minimap.css';

let modeler = null;

const getEmptyBpmnTemplate = () => {
  return `<?xml version="1.0" encoding="UTF-8"?>
<definitions xmlns="http://www.omg.org/spec/BPMN/20100524/MODEL" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xmlns:xsd="http://www.w3.org/2001/XMLSchema" 
xmlns:bpmndi="http://www.omg.org/spec/BPMN/20100524/DI" 
xmlns:omgdc="http://www.omg.org/spec/DD/20100524/DC" 
xmlns:omgdi="http://www.omg.org/spec/DD/20100524/DI" 
xmlns:camunda="http://camunda.org/schema/1.0/bpmn" 
id="Definitions_1" targetNamespace="http://bpmn.io/schema/bpmn" 
xmlns:modeler="http://camunda.org/schema/modeler/1.0" 
modeler:executionPlatform="Camunda Platform" 
modeler:executionPlatformVersion="7.16.0">
</definitions>`;
};

onMounted(() => {
  initModeler();
});

onUnmounted(() => {
  if (modeler) {
    modeler.destroy();
    modeler = null;
  }
});

const initModeler = () => {
  // 创建BPMN建模器实例
  modeler = new BpmnModeler({
    container: '#canvas',
    propertiesPanel: {
      parent: '#properties-panel-parent'
    },
    additionalModules: [
      BpmnPropertiesPanelModule,
      BpmnPropertiesProviderModule,
      minimapModule
    ],
    moddleExtensions: {
      camunda: {
        name: 'camunda',
        uri: 'http://camunda.org/schema/1.0/bpmn',
        prefix: 'camunda',
        xml: {
          tagAlias: 'lowerCase'
        }
      }
    }
  });

  // 加载初始模板
  loadTemplate();
};

const loadTemplate = () => {
  if (!modeler) return;

  modeler.importXML(getEmptyBpmnTemplate())
    .then(() => {
      console.log('模板加载成功');
      // 居中显示流程
      const canvas = modeler.get('canvas');
      canvas.zoom('fit-viewport');
    })
    .catch(err => {
      console.error('模板加载失败:', err);
    });
};

const newDiagram = () => {
  if (confirm('确定要创建新流程吗？未保存的内容将会丢失。')) {
    loadTemplate();
  }
};

const saveDiagram = async () => {
  if (!modeler) return;

  try {
    const { xml } = await modeler.saveXML({ format: true });
    // 保存到本地存储
    localStorage.setItem('lastDiagram', xml);
    alert('流程保存成功！');
  } catch (err) {
    console.error('保存流程失败:', err);
    alert('保存失败，请重试。');
  }
};

const deployDiagram = async () => {
  if (!modeler) return;

  try {
    const { xml } = await modeler.saveXML({ format: true });
    const result = await workflowService.deployProcess({ bpmnXml: xml });
    alert('流程部署成功！');
    console.log('部署结果:', result);
  } catch (err) {
    console.error('部署流程失败:', err);
    alert('部署失败，请重试。');
  }
};
</script>

<style scoped>
.process-designer {
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.toolbar {
  padding: 10px;
  background-color: #f5f5f5;
  border-bottom: 1px solid #ddd;
  display: flex;
  gap: 10px;
}

.btn {
  padding: 8px 16px;
  border: 1px solid #ddd;
  background-color: #fff;
  cursor: pointer;
  border-radius: 4px;
  transition: all 0.3s ease;
}

.btn:hover {
  background-color: #f0f0f0;
}

.btn-primary {
  background-color: #42b983;
  color: white;
  border-color: #42b983;
}

.btn-primary:hover {
  background-color: #35495e;
  border-color: #35495e;
}

.editor-container {
  flex: 1;
  display: flex;
  position: relative;
}

.canvas {
  flex: 1;
  background-color: #fafafa;
}

.properties-panel {
  width: 300px;
  border-left: 1px solid #ddd;
  overflow-y: auto;
  background-color: #fff;
}
</style>